#include <ncurses.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <menu.h>
#include <form.h>

#define MAX_SIZE 1024

void single_entry(char *arg1);
void display_entry(char *arg1);
void display_menu(WINDOW *menu_win);
void getShort(char* word);
void getFile(char* arg1,char *outname);
void print_menu(WINDOW *menu_win,int highlight,char **choices, int n_choices);
void print_prompt(WINDOW *menu_win);
void print_about(WINDOW *menu_win);
void print_usage();

int main(int argc, char **argv)
{

	if (argc == 1) 
	{
		WINDOW *menu_win;
		initscr();/*initiate screen*/
		clear();/*clear screen*/
		raw();
		noecho();/*dont print characters you type*/
		cbreak();
		start_color();
		curs_set(0);/*dont show cursor*/
		menu_win = newwin(0, 0, 0, 0);
		refresh();

		display_menu(menu_win);

		clrtoeol();
		refresh();
		endwin();

		/* it clears up the screan, works only on ANSI terminal*/
		printf("\033[2J\033[0;0f");

		return 0;
	}
	else if (argc==2)
	{
		/* 
		   I think this is the way we wanted... 
		   calling display_entry makes us to use this program like man page.. 
		   opinions?
		 */

		/*single_entry(argv[1]);*/
		
		display_entry(argv[1]);
	}
	else
	{ 
		/* getopt*/

		int ch;
		while ((ch = getopt(argc, argv, "s:")) != -1) {
			switch (ch) {

				/* quick view opt */
				/* need to secure args... */
				case 's':
					getShort(argv[2]);
					break;

				case '?':
				default:
					print_usage();
			}
		}
	}
	return 0;
}

void single_entry(char *arg1)
{
	char *buffer=malloc( MAX_SIZE );
	char *outname = "outfile"; 
	int i,fd;

	getFile( arg1,outname );

	fd = open(outname,O_RDONLY);
	i=read(fd,buffer,MAX_SIZE-1);
	if (i==-1)
	{
		perror("Read call failed");
	}

	i = system("cat outfile");
	if (i==-1)
	{
		perror("cat");
	}
	close(fd);
	free(buffer);
}

void display_config(WINDOW *menu_win)
{
	int x, y;
	x = COLS/2;
	y = LINES/2;
	noecho();
	mvwprintw(menu_win,y+10, x-35, "%s", "Configuration");

	refresh();
	getch();
	mvwprintw(menu_win, y+10, x-35, "%s", "             ");
}

/*You want to view an entry, so the perl script
 *is run to grab the entry, and then you read the 
 *entry from the outfile using less*/
void display_entry(char *arg1)
{
	char *buffer=malloc( MAX_SIZE );
	char *outname = "outfile\0";
	int i,fd;

	getFile(arg1,outname);

	fd = open(outname,O_RDONLY);
	i=read(fd,buffer,MAX_SIZE-1);
	if (i==-1)
	{
		perror("Read call failed");
	}

	i=system("less outfile");
	if (i==-1)
	{
		perror("less call failed");
	}
	close(fd);
	free(buffer);
	/*When you quit less, you want to close that current window*/
	clrtoeol();
	refresh();
	endwin();
}

void display_menu(WINDOW *menu_win)
{
	int highlight=1;
	int choice =0;
	int c;
	char *choices[] = {"Lookup Term","About","Exit"};
	int n_choices = sizeof(choices)/sizeof(char *);

	keypad(menu_win, TRUE);  
	print_menu(menu_win, highlight,choices,n_choices);

	/*you print the menu, and then catch the keypresses
	 *to navigate around it*/
	while(1)
	{
		c = wgetch(menu_win);
		switch(c)
		{
			case KEY_UP:
				if(highlight == 1)
					highlight = n_choices;
				else
					--highlight;
				break;
			case KEY_DOWN:
				if(highlight == n_choices)
					highlight = 1;
				else 
					++highlight;
				break;
			case 10:
				/*you pressed enter*/
				choice = highlight;
				if (highlight==1)
				{
					wrefresh(menu_win);
					/*if you want to search, a
					 *prompt comes up and shows the entry*/
					print_prompt(menu_win);
					break;
				}
				//if (highlight==3)
				//{
				//	clear();
				//		box(menu_win, 0, 0);
				//		display_config(menu_win);    
				//		wrefresh(menu_win);
				//		break;
				//}
				if (highlight==2)
				{
					/*about*/
					wrefresh(menu_win);
					print_about(menu_win);
					break;
				}
				if (highlight==n_choices)
				{
					/*exit*/
					wrefresh(menu_win);
					return;
				}
				else
				{
					break;
				}
				break;
		}
		print_menu(menu_win, highlight,choices,n_choices);
	}
	return;
}


/* 
   to show a short paragraph of txt. I cheated to use unix command but if you want to actually parse 
   the entire page, we can do that later. (also this is faster than fetching/parsing data from wiki
 */
void getShort(char* word)
{	
	int i;
	char *command = malloc(strlen("dig +short txt ")+
			strlen(word)+
			strlen(".wp.dg.cx") + 3);

	strcpy(command,"dig +short txt ");
	strcat(command,word);
	strcat(command,".wp.dg.cx");
	printf("COMMAND: %s\n",command);
	i=system(command);
	if (i==-1)
	{
		perror("System call failed");
	}
	free(command);
}

void getFile(char* arg1,char *outname)
{
	int i;
	char *command = malloc(strlen("./getPage.pl ")+
			strlen(arg1)+
			strlen(" >")+
			strlen(outname)+3);

	strcpy(command,"./getPage.pl ");
	strcat(command,arg1);
	strcat(command," >");
	strcat(command,outname);

	i=system(command);
	if (i==-1)
	{
		perror("System call failed");
	}
	free(command);
}

void print_menu(WINDOW *menu_win,int highlight,char **choices, int n_choices)
{
	int x, y, i;
	init_pair(1,COLOR_BLUE,COLOR_BLACK);
	x = COLS/2;
	y = LINES/2;
	box(menu_win, 0, 0);
	for(i = 0; i < n_choices; ++i)
	{
		wattron(menu_win,COLOR_PAIR(1)|A_BOLD);
		if(highlight == i + 1) 
		{
			wattron(menu_win, A_REVERSE);
			mvwprintw(menu_win, y, x, "%s", choices[i]);
			wattroff(menu_win, A_REVERSE); 
		}
		else
			mvwprintw(menu_win, y, x, "%s", choices[i]);
		++y;
		wattroff(menu_win,COLOR_PAIR(1)|A_BOLD);
	}
	refresh();
}

void print_prompt(WINDOW *menu_win)
{
	int x,y;
	x= COLS/2;
	y= LINES/2;
	char *string_input=malloc(256);
	wattron(menu_win,COLOR_PAIR(1));
	mvwprintw(menu_win, y+10, x-35, "%s", "Term you would like to search for: ");
	refresh();
	echo();
	mvwgetnstr(menu_win,y+10,x,string_input,255);
	refresh();
	wattroff(menu_win,COLOR_PAIR(1)|A_BOLD);
	/*erases*/
	mvwprintw(menu_win, y+10, x-38, "%s", "                                                                                       ");
	display_entry(string_input);
	free(string_input);
	refresh();
}

void print_about(WINDOW *menu_win)
{
	int x,y;
	x=COLS/2;
	y=LINES/2;
	wattron(menu_win,COLOR_PAIR(1));
	mvwprintw(menu_win, y+10, x-38, "%s", "Developed by Andrey Tydnyuk, Peter Appleby, Dan Pomeroy and Jeung Won Kim");
	wattroff(menu_win,COLOR_PAIR(1));
	refresh();
	wgetch(menu_win);
	/*this erases...*/
	mvwprintw(menu_win, y+10, x-38, "%s", "                                                                                        ");
	refresh();
}


void print_usage()
{
	printf("Usage of manwiki:\n");
	printf("      $./mw\n");
	printf("      $./mw <keyword>\n");
	printf("      You need either one or no arguments with options.\n");
	printf("      -s quick view\n");
	printf("          example: $./mw -s <keyword>\n");
}
